<template>
  <div class="moment-form-page">
    <div class="form-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h1 class="title">{{ isEditMode ? '编辑动态' : '记录心情' }}</h1>
      <div></div>
    </div>

    <div class="form-content" v-loading="loading">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="moment-form"
        v-if="!loading || !isEditMode"
      >
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="8"
            placeholder="记录下此刻的心情..."
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="心情">
          <el-select v-model="form.mood" placeholder="选择心情" clearable>
            <el-option
              v-for="mood in moodOptions"
              :key="mood.value"
              :label="mood.label"
              :value="mood.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="图片" v-if="!isEditMode">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            accept="image/*"
            multiple
            :limit="9"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="标签">
          <div class="tag-input-container">
            <el-tag
              v-for="tag in form.tags"
              :key="tag"
              closable
              @close="removeTag(tag)"
              class="tag-item"
            >
              #{{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="inputRef"
              v-model="inputValue"
              class="tag-input"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button
              v-else
              class="add-tag-btn"
              size="small"
              @click="showInput"
            >
              + 添加标签
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="可见性">
          <el-radio-group v-model="form.isPrivate">
            <el-radio :label="false">
              <el-icon><View /></el-icon>
              公开
            </el-radio>
            <el-radio :label="true">
              <el-icon><Lock /></el-icon>
              私密
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
            size="large"
          >
            {{ isEditMode ? '保存' : '发布' }}
          </el-button>
          <el-button @click="goBack" size="large">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElForm, type UploadFile, type UploadFiles } from 'element-plus'
import { ArrowLeft, Plus, View, Lock } from '@element-plus/icons-vue'
import { useMoments } from '../composables/useMoments'
import { MoodType, type CreateMomentRequest, type UpdateMomentRequest } from '../types'

const router = useRouter()
const route = useRoute()
const { loading, currentMoment, createMoment, updateMoment, fetchMomentDetail } = useMoments()

const formRef = ref<InstanceType<typeof ElForm>>()
const inputRef = ref()
const submitLoading = ref(false)

// 判断是否为编辑模式
const isEditMode = computed(() => !!route.params.id)

// 表单数据
const form = reactive<CreateMomentRequest | UpdateMomentRequest>({
  content: '',
  mood: undefined,
  images: [],
  tags: [],
  isPrivate: false
})

// 文件列表（仅创建模式）
const fileList = ref<UploadFiles>([])

// 标签输入
const inputVisible = ref(false)
const inputValue = ref('')

// 心情选项
const moodOptions = [
  { value: MoodType.HAPPY, label: '😊 开心' },
  { value: MoodType.SAD, label: '😢 难过' },
  { value: MoodType.EXCITED, label: '🎉 兴奋' },
  { value: MoodType.PEACEFUL, label: '😌 平静' },
  { value: MoodType.ANXIOUS, label: '😰 焦虑' },
  { value: MoodType.GRATEFUL, label: '🙏 感恩' },
  { value: MoodType.THOUGHTFUL, label: '🤔 沉思' },
  { value: MoodType.NOSTALGIC, label: '😌 怀念' }
]

// 表单验证规则
const rules = {
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 1, max: 2000, message: '内容长度在 1 到 2000 个字符', trigger: 'blur' }
  ]
}

// 处理图片变化（仅创建模式）
const handleImageChange = (file: UploadFile) => {
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      const imageUrl = e.target?.result as string
      if (!form.images) form.images = []
      form.images.push(imageUrl)
    }
    reader.readAsDataURL(file.raw)
  }
}

// 移除图片（仅创建模式）
const handleImageRemove = (file: UploadFile) => {
  if (form.images && file.url) {
    const index = form.images.indexOf(file.url)
    if (index > -1) {
      form.images.splice(index, 1)
    }
  }
}

// 显示标签输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 确认输入标签
const handleInputConfirm = () => {
  if (inputValue.value && !form.tags?.includes(inputValue.value)) {
    if (!form.tags) form.tags = []
    form.tags.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 移除标签
const removeTag = (tag: string) => {
  if (form.tags) {
    const index = form.tags.indexOf(tag)
    if (index > -1) {
      form.tags.splice(index, 1)
    }
  }
}

// 初始化表单数据（编辑模式）
const initForm = () => {
  if (currentMoment.value) {
    Object.assign(form, {
      id: currentMoment.value.id,
      content: currentMoment.value.content,
      mood: currentMoment.value.mood,
      images: currentMoment.value.images || [],
      tags: currentMoment.value.tags || [],
      isPrivate: currentMoment.value.isPrivate
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (valid) {
      submitLoading.value = true
      let success = false

      if (isEditMode.value) {
        // 编辑模式
        success = await updateMoment(form as UpdateMomentRequest)
      } else {
        // 创建模式
        success = await createMoment(form as CreateMomentRequest)
      }

      if (success) {
        goBack()
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

onMounted(async () => {
  if (isEditMode.value) {
    const momentId = route.params.id as string
    if (momentId) {
      await fetchMomentDetail(momentId)
      initForm()
    }
  }
})
</script>

<style scoped>
.moment-form-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
}

.title {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.form-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.moment-form {
  max-width: 600px;
  margin: 0 auto;
  background: var(--el-bg-color);
  padding: 24px;
  border-radius: 12px;
  border: 1px solid var(--el-border-color-light);
}

.tag-input-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.add-tag-btn {
  border: 1px dashed var(--el-border-color);
  color: var(--el-text-color-placeholder);
}

:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 80px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
